package v1

import (
	"bytes"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/spectacleCase/develop_auth_platform/global"
	"github.com/spectacleCase/develop_auth_platform/models"
	"github.com/spectacleCase/develop_auth_platform/models/request"
	"log"
	"net/http"
	"time"
)

type Test struct{}

func (Test) Verify() gin.HandlerFunc {
	return func(c *gin.Context) {
		var test request.Test
		if err := c.ShouldBind(&test); err != nil {
			models.FailWithMessage("参数有误", c)
			return
		}

		// 查找应用
		var targetApp *models.Application
		for _, app := range global.ApplicationList {
			if app != nil && app.Id == test.AppId {
				targetApp = app
				break
			}
		}

		if targetApp == nil {
			models.FailWithMessage("应用不存在", c)
			return
		}

		// 验证密钥
		if !models.VerifyKeyPair(targetApp.PrKey, test.PuKey) {
			models.FailWithMessage("密钥验证失败", c)
			return
		}

		// 验证通过后异步发送回调
		go sendCallback(targetApp.CallbackUrl, map[string]interface{}{
			"event":     "verification_success",
			"app_id":    targetApp.Id,
			"timestamp": time.Now().Unix(),
			//"signature":  generateSignature(targetApp.PrKey), // 可选：添加签名
			"mock_data": generateMockData(),
		})

		models.OkWithData(gin.H{
			"message": "验证成功，回调已触发",
			"app_id":  targetApp.Id,
		}, c)
	}
}

// 发送回调请求（带重试机制）
func sendCallback(url string, data interface{}) {
	maxRetries := 3
	retryDelay := 2 * time.Second

	jsonData, _ := json.Marshal(data)

	for i := 0; i < maxRetries; i++ {
		resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
		if err == nil && resp.StatusCode == http.StatusOK {
			log.Printf("✅ 回调成功 | URL: %s | 数据: %s", url, string(jsonData))
			resp.Body.Close()
			return
		}

		if err != nil {
			log.Printf("⚠️ 回调失败(尝试 %d/%d) | URL: %s | 错误: %v",
				i+1, maxRetries, url, err)
		} else {
			log.Printf("⚠️ 回调失败(尝试 %d/%d) | URL: %s | 状态码: %d",
				i+1, maxRetries, url, resp.StatusCode)
			resp.Body.Close()
		}

		if i < maxRetries-1 {
			time.Sleep(retryDelay)
		}
	}

	log.Printf("❌ 回调最终失败 | URL: %s", url)
}

// 生成模拟数据
func generateMockData() map[string]interface{} {
	return map[string]interface{}{
		"user": map[string]string{
			"id":    "mock_user_123",
			"name":  "测试用户",
			"email": "test@example.com",
		},
		"resources":  []string{"res1", "res2", "res3"},
		"quota":      1000,
		"expires_at": time.Now().Add(24 * time.Hour).Unix(),
	}
}
